<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="子标题" prop="transTitle">
              <el-input
                  v-model="queryParams.transTitle"
                  placeholder="请输入"
                  clearable
                  style="width: 240px"
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>-->
      <el-form-item label="发表时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          :default-time="['00:00:00','23:59:59']"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="isAdmin"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete(ids)"
          :disabled="ids.length===0"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
              >导出
              </el-button>
            </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" border :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column align="center" show-overflow-tooltip label="标题" prop="title"/>
      <el-table-column align="center" show-overflow-tooltip label="来源" prop="origin"/>
      <el-table-column align="center" show-overflow-tooltip label="作者" prop="author"/>
      <el-table-column align="center" show-overflow-tooltip label="发布日期" prop="createTime"/>
      <el-table-column align="center" show-overflow-tooltip label="审核状态" prop="auditStatus">
        <template slot-scope="{row}">{{ auditStatusMap[row.auditStatus] }}</template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip label="备注" prop="content">
        <template slot-scope="{row}">
          <text-overflow :text="row.content"></text-overflow>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-if="((scope.row.createUserId==id&&!scope.row.auditStatus==0&&!scope.row.auditStatus==1)) || scope.row.createUserId==id&&scope.row.auditStatus==2 || isAdmin"
          >编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handlePreview(scope.row)"
          >预览
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDownload(scope.row)"
          >下载
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete([scope.row.id])"
            v-if="((scope.row.createUserId==id&&scope.row.auditStatus==0) || scope.row.createUserId==id&&scope.row.auditStatus==2) || isAdmin"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="getAuditFeedbackChange(scope.row)"
            v-if="scope.row.auditStatus==2"
          >驳回原因
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.curPage"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="来源" prop="origin">
          <el-input v-model="form.origin" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="内容" prop="enclosure">
          <el-upload style="width: 100%;"
            drag
            class="upload-demo"
            accept=".docx"
            :before-upload="beforeUpload"
            action="https://jsonplaceholder.typicode.com/posts/"
            :http-request="uploadFile"
            :multiple="false"
            :on-change="handleChangeFiles"
            :file-list="fileList"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip" style="color: red;">只能上传docx文件，且不超过5M, 修改时请上传新的附件！</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" style="width: 100%" class="fsfdasfsaf">
          <el-input
            type="textarea"
            style="width: 100%;"
            :autosize="{ minRows: 6, maxRows: 12}"
            placeholder="请输入备注"
            v-model="form.content"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 文件预览弹窗 -->
    <el-dialog
      title="在线预览"
      :visible.sync="previewVisible"
      width="60%"
    >
      <vue-office-docx :src="previewUrl" @rendered="rendered"/>
    </el-dialog>
    <el-dialog
      title="审核驳回反馈"
      :visible.sync="feedbackVisible"
      width="60%"
    >
      <div style="font-size: 16px;font-weight: bold; margin-bottom: 10px;">审核不通过原因:</div>
      <el-row style="margin-bottom: 10px;">
        <el-col :span="24">
          <el-card style="width: 100%; height: 20vh;">
            <div v-html="feedback.auditRemark"></div>
          </el-card>
        </el-col>
      </el-row>
      <div style="font-size: 16px;font-weight: bold; margin-bottom: 10px;">审核时间:</div>
      <el-row style="margin-bottom: 10px;">
        <el-col :span="24">
          <el-card>
            <div v-html="feedback.createTime"></div>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>

  </div>

</template>

<script>
import {changeRoleStatus, deptTreeSelect} from '@/api/system/role'
import {roleMenuTreeselect} from '@/api/system/menu'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {DomEditor} from '@wangeditor/editor'
import VueOfficeDocx from '@vue-office/docx'
import '@vue-office/docx/lib/index.css'
import TextOverflow from '@/views/qyxx/components/text-overflow.vue'
import {
  addOtherArtcle,
  deletemanu,
  editOtherArtcle,
  getAuditFeedback,
  getCustomArticleList,
  getFileEnclosurePath
} from '@/api'
import {mapGetters} from 'vuex'

export default {
  name: 'dp',
  components: {TextOverflow, Editor, Toolbar, VueOfficeDocx},
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      tableList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      deptExpand: true,
      deptNodeAll: false,
      feedbackVisible: false,
      feedback: {},
      // 日期范围
      dateRange: [],
      // 数据范围选项
      dataScopeOptions: [
        {
          value: '1',
          label: '全部数据权限'
        },
        {
          value: '2',
          label: '自定数据权限'
        },
        {
          value: '3',
          label: '本部门数据权限'
        },
        {
          value: '4',
          label: '本部门及以下数据权限'
        },
        {
          value: '5',
          label: '仅本人数据权限'
        }
      ],
      // 文件预览
      previewUrl: '',
      // 弹出层是否可见
      previewVisible: false,
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        curPage: 1,
        pageSize: 10,
        title: undefined,
        transTitle: undefined,
        status: undefined
      },
      // 表单参数
      form: {title: '', origin: '', author: '', content: ''},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表单校验
      rules: {
        title: [
          {required: true, message: '标题不能为空', trigger: 'blur'}
        ],
        origin: [
          {required: true, message: '来源不能为空', trigger: 'blur'}
        ],
        author: [
          {required: true, message: '作者不能为空', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '备注不能为空', trigger: 'blur'}
        ],
        // enclosure: [
        //   {required: true, message: '文章内容附件未上传', trigger: 'blur'}
        // ]
      },
      editor: null,
      toolbarConfig: {excludeKeys: ['emotion', 'insertLink', 'group-image', 'group-video']},
      editorConfig: {placeholder: '请输入内容...'},
      mode: 'default', // or 'simple'
      classifyId: this.$route.query.id,
      selectTableList: [],
      ids: [],
      fileList: [],
      auditStatusMap: {0: '审核中', 1: '审核通过', 2: '审核不通过'}

    }
  },

  computed: {...mapGetters(['isAdmin', 'id'])},
  created() {
    this.getList()
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      // console.log(this.editor.getAllMenuKeys())
      const toolbar = DomEditor.getToolbar(this.editor)
      // console.log(DomEditor, this)
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true
      getCustomArticleList({
        // classifyId: this.classifyId,
        deleteData: 0,
        // auditStatus:"",//审核状态 (0:审核中,1:审核通过,2:审核不通过)
        ...this.queryParams,
        startTime: this.dateRange && this.dateRange[0],
        endTime: this.dateRange && this.dateRange[1]
      }).then(res => {
        this.tableList = res.data.records
        this.total = res.data.total
      }).finally(() => {
        this.loading = false
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys()
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.menus
        return response
      })
    },
    /** 根据角色ID查询部门树结构 */
    getDeptTree(roleId) {
      return deptTreeSelect(roleId).then(response => {
        this.deptOptions = response.depts
        return response
      })
    },
    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === '0' ? '启用' : '停用'
      this.$modal.confirm('确认要"' + text + '""' + row.title + '"角色吗？').then(function () {
        return changeRoleStatus(row.roleId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
      }).catch(function () {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        title: undefined,
        scrapeDate: undefined,
        publishDate: undefined,
        transTitle: undefined,
        keyword: undefined,
        author: undefined,
        language: undefined,
        typeTag: undefined,
        url: undefined,
        abstractStr: undefined,
        transAbstract: undefined,
        fwb: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.curPage = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectTableList = selection
      this.ids = selection.map(item => item.id)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.title = '修改'
      this.open = true
      this.form = {...row}
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let params = {...this.form}
          let formData = new FormData()
          for (let key in params) {
            if (params[key] !== void 0) {
              formData.append(key, params[key])
            }
          }
          if (this.fileList.length === 1) {
            formData.append('enclosure', this.fileList[0].raw)
            // params.enclosure = formData
          }

          if (this.form.id) {
            editOtherArtcle(formData).then(res => {
              this.open = false
              this.getList()
            })
          } else {
            addOtherArtcle(formData).then(res => {
              this.open = false
              this.getList()
            })
          }
          this.open = false
        }
      })
    },
    getAuditFeedbackChange(row) {
      this.feedbackVisible = true
      this.feedback = getAuditFeedback(row.id).then(response => {
        this.feedback = response.data
      }).catch(error => {
        console.log(error)
      })
    },
    /** 获取附件链接 */
    getEnclosureUrl(row) {
      getFileEnclosurePath({id: row.id}).then(response => {
        this.previewUrl = response.data[0]
      }).catch(error => {
        console.log(error)
      })
    },
    /** 预览按钮操作 */
    handlePreview(row) {
      this.previewVisible = true
      this.previewUrl = ''
      this.getEnclosureUrl(row)
    },
    rendered() {
      console.log('渲染完成')
      console.log(this.previewUrl)
    },
    /** 下载文件 */
    downloadFile() {
      const aLink = document.createElement('a')
      aLink.href = this.previewUrl
      aLink.click()
    },
    handleDownload(row) {
      this.getEnclosureUrl(row)
      setTimeout(() => {
        this.downloadFile()
      }, 1000)
    },
    /** 收藏按钮操作 */
    handleCollection() {
      // TODO 收藏功能
    },

    /** 删除按钮操作 */
    handleDelete(ids) {
      this.$modal.confirm('是否确认删除？').then(() => {
        deletemanu(ids).then(res => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/role/export', {
        ...this.queryParams
      }, `role_${new Date().getTime()}.xlsx`)
    },
    uploadFile({file}) {
      // console.log(this.fileList)
    },
    handleChangeFiles(file, fileList) {
      this.fileList = fileList.slice(-1)
    },
    tableRowClassName({ rowIndex }) {
      return rowIndex % 2 === 0 ? 'even-row' : 'odd-row';
    },
    // 文件格式和大小验证函数
    beforeUpload(file) {
      const isDocx = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      const isLtMaxSize = file.size <= 5 * 1024 * 1024;

      if (!isDocx) {
        this.$message.error('仅支持上传 .docx 格式的文件');
        return false;
      }
      if (!isLtMaxSize) {
        this.$message.error('文件大小不能超过 5MB');
        return false;
      }
      return true;
    },
  }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss">
.el-tooltip__popper {
  background-color: #fff !important;
  color: #606266 !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1) !important;
  max-width: 600px;
}

/*
.el-table .cell.el-tooltip {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 5;
  display: -moz-box;
  -moz-box-orient: vertical;
  -moz-line-clamp: 5;
  word-break: break-all;
  white-space: normal;
}*/
</style>
<style scoped lang="scss">
.even-row {
  background-color: rgb(199, 1, 61); /* 偶数行背景色 */
}
.odd-row {
  background-color: #ffffff; /* 奇数行背景色 */
}
.fsfdasfsaf {
  ::v-deep .el-form-item__content {
    width: calc(100% - 100px);
  }
}

</style>
